from django.contrib.auth.hashers import make_password, check_password
from django.shortcuts import render, redirect
from django.http import HttpResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework_jwt.authentication import api_settings

from meiduo import settings
from django.core.mail import send_mail
from utils.captcha.captcha import captcha
from utils import Common
from utils.Common import getRedis, send_message


from .models import *
from .ser import *


import re
import redis
import random


class Register(APIView):
    def post(self,request):
        # 获取用户名
        username = request.data.get('username')
        # 判断用户名是否为空 是否符合5-20标准
        arr = re.search('\w{5,20}', username)
        if not arr:
            return Response({'code': 10010, 'msg': '账户不符合标准'})
        # 去users表中查找用户名是否存在
        nameflag = User.objects.filter(username=username).first()
        if nameflag:
            # 假如存在，提示已经存在不能注册
            return Response({'code':10011,'msg':'用户已经存在不能注册'})
        # 假如不存在 提示可以注册

        # 获取密码
        passowrd1 = request.data.get('password1')
        passowrd2 = request.data.get('password2')
        # 判断用户名是否为空 是否符合8-20标准
        passflag = re.search('\w{8,20}', passowrd2)
        if not passflag:
            return Response({'code': 10012, 'msg': '密码不符合标准'})
        if passowrd1 != passowrd2:
            return Response({'code': 10013, 'msg': '两次密码不一致'})

            # 获取手机号
        mobile = request.data.get('mobile')
        # 判断用户名是否为空 是否符合手机号标准
        arr = re.search('[1][345678][0-9]{8}',mobile)
        if not arr:
            return Response({'code': 10014, 'msg': '手机号不符合标准'})
        # 去users表中查找手机号是否存在
        mobileflag = User.objects.filter(mobile=mobile).first()
        if mobileflag:
            return Response({'code': 10015, 'msg': '手机号已经存在不能注册'})
        # 假如不存在 提示可以注册

        # 是否同意协议
        agree = request.data.get('agree')
        if not agree:
            return Response({'code': 10016, 'msg': '请选择'})

        # 注册添加到user表
        # request.data['password1'] = make_password(request.data.get('password1'))
        # print(make_password)
        ser = UserSer(data={'username':username,'password':make_password(passowrd1),'mobile':mobile,'agree':agree})
        if ser.is_valid():
            ser.save()
        else:
            print(ser.errors)
            print(request.data)
        return Response({'code': 200,'msg': '注册成功'})


# 生成验证码图片 流
class ImageCode(APIView):
    # 生成图片验证码
        def get(self, request):
            # 获取uuid
            uuid = request.GET.get('uuid')
            # 生成验证码图片
            name, text, pic = captcha.generate_captcha()
            # 获取redis连接
            redis_con = Common.getRedis()
            # 图片验证码存储在redis里面，设置过期时间
            redis_con.setex(uuid, 60, text)  # 以秒为单位
            # 以图片的方式输出
            return HttpResponse(pic, content_type='image/jpg')


class SendSms(APIView):
    def get(self, request):
        # 接收客户端发送的数据
        imagecode = request.GET.get('imagecode')
        mobile = request.GET.get('mobile')
        uuid = request.GET.get('uuid')
        if not all([imagecode, mobile]):
            return Response({'code': 10017})
        # 验证图片验证码
        conn = getRedis()
        # redis中取验证码
        code = conn.get(uuid)
        if code:
            code = str(code, encoding='utf8')
            # 图片验证码对比
            if imagecode.lower() == code.lower():
                # 验证通过后调用发送短信接口
                sms_code = random.randint(10000, 99999)
                result = send_message(mobile, sms_code, 1)
                # 假如短信验证码发送成功
                if result:
                    # redis存短信验证码
                    conn.setex(mobile, 60, sms_code)
                    # 把图片验证码从redis删除
                    conn.delete(uuid)
                    return Response({'code': 200,'msg':sms_code})
                else:
                    return Response({'code': 10020})
            else:
                return Response({'code': 10019})
        else:
            return Response({'code': 10018})


class UserByid(APIView):
    def get(self, request):
        user = User.objects.all()
        user_data = UserSer(user, many=True)
        return Response(user_data.data)


class Test(APIView):
    def get(self, request):
        msg = '<a href="http://localhost:8080/#/register" target="_blank">点击激活</a>'
        result = send_mail('注册激活', '绑定邮箱', settings.EMAIL_HOST_USER, ['shijp3103719511@163.com',
                                                                      '3103719511@qq.com'], html_message=msg)


class SendMail(APIView):
    def get(self, request):
        email = request.GET.get('email')
        userid = request.GET.get('userid')
        user = User.objects.filter(email=email).first()
        if user:
            return Response({'code': 10050})
        token = random.randint(10000, 99999)
        message = '请点击<a href="http://localhost:8000/users/valid_email/?token=%s&userid=%s">链接</a>进行激活'%(token,userid)
        result = send_mail('绑定邮箱验证', '', settings.EMAIL_HOST_USER, [email], html_message=message)
        if result:
            conn = getRedis()
            conn.setex(token, 120, email)
            print(result)
            return Response({'code': 200})
        else:
            return Response({'code': 10051})


class ValidEmail(APIView):
    def get(self, request):
        token = request.GET.get('token')
        userid = request.GET.get('userid')
        conn = getRedis()
        email = conn.get(token)
        if email:
            email = str(email, encoding='utf8')
            User.objects.filter(id=userid).update(email=email)
            print(email)
            return redirect('http://localhost:8000/#/userinfo')
        return redirect('http://localhost:8000/#/userinfo')


class ProviceManage(APIView):
    def get(self, request):
        pid = request.GET.get('pid')
        if pid:
            area = Area.objects.filter(pid_id=pid).all()
        else:
            area = Area.objects.filter(pid__isnull=True).all()
        ser = AreaSer(area, many=True)
        return Response({'code': 200, 'list': ser.data})


class UserPass(APIView):
    def get(self, request):
        pas = request.GET.get('pas')
        password = User.objects.get('password')
        if password == pas:
            return Response({'code': '200', 'msg': '正确'})
        else:
            return Response({'code': '40050', 'msg': '不正确'})


class AddressManage(APIView):
    def post(self, request):
        ser = AddressSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200})
        else:
            print(ser.errors)
            return Response({'code': 40060})

    def get(self, request):
        userid = request.GET.get('userid')
        address = Address.objects.filter(user_id=userid).all()
        ser = ShowAddressSer(address, many=True)
        return Response({'code': 200, 'list': ser.data})
